package serv

import (
	"encoding/json"
	"erp/model"
	"erp/utils"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func LoginCtrl(c *gin.Context) {
	c.HTML(http.StatusOK, "login/index.html", nil)
}

func LoginCheckCtrl(c *gin.Context) {
	rawData, _ := c.GetRawData()
	var params map[string]string
	_ = json.Unmarshal(rawData, &params)

	username := params["username"]
	password := params["password"]

	userData := model.User{}
	userData = userData.GetByUsername(username)

	if userData.Password == password {
		c.SetCookie("token", fmt.Sprintf("%d|%s|%d", userData.Id, utils.MD5(userData.Username), time.Now().Unix()), 0, "", "", false, true)
		c.JSON(200, map[string]interface{}{
			"status": 200,
		})
	} else {
		c.JSON(200, map[string]interface{}{
			"status": 404,
			"msg":    "认证失败",
		})
	}
}
